import { HttpResponse, type JsonBodyType } from 'msw';

const baseCorsHeaders: Record<string, string> = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
};

function mergeHeaders(headers?: HeadersInit): Headers {
  const merged = new Headers(baseCorsHeaders);
  if (headers) {
    const extra = new Headers(headers);
    extra.forEach((value, key) => {
      merged.set(key, value);
    });
  }
  return merged;
}

export function withCors(init?: ResponseInit): ResponseInit {
  if (!init) {
    return {
      headers: mergeHeaders(),
    };
  }

  const { headers, ...rest } = init;
  return {
    ...rest,
    headers: mergeHeaders(headers),
  };
}

export function jsonResponse<T extends JsonBodyType>(data: T, init?: ResponseInit) {
  return HttpResponse.json(data, withCors(init));
}
